package com.losl.framework.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.validation.Valid;

import cn.hutool.core.util.ArrayUtil;
import com.losl.common.annotation.Log;
import com.losl.common.core.domain.model.LoginUser;
import com.losl.common.enums.BusinessType;
import com.losl.common.enums.LogType;
import com.losl.common.util.ServletUtils;
import com.losl.common.util.StringUtils;
import com.losl.framework.web.service.TokenService;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.losl.common.core.domain.Result;
import com.losl.common.core.domain.BaseController;
import com.losl.common.exception.CustomException;

import com.losl.system.pojo.Comment;
import com.losl.system.service.CommentService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;


/**
 * 评论表 控制器
 * @author maxwell
 * @date 2021-06-04
 */
@RestController
@RequestMapping("/comment")
@Api(value = "评论表-API", tags = { "评论表相关接口" })
public class CommentController extends BaseController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private TokenService tokenService;

    /**
     * 评论表分页列表
     */
    @ApiOperation("分页查询评论表")
    @ApiImplicitParam(name = "comment", value = "评论表实体", paramType = "query", dataType = "Comment")
    @GetMapping("/page")
    public Result page(Comment comment) {
        if(StringUtils.isNull(comment)){
            return Result.error("实体类不能为空");
        }
        Page<Comment> page = getPage();
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<Comment>(comment);
        IPage<Comment> pageInfo = commentService.page(page, queryWrapper);
        return Result.success().put("total", pageInfo.getTotal()).put("rows", pageInfo.getRecords());
    }

    /**
     * 查询评论表列表
     */
    @ApiOperation("查询评论表列表")
    @ApiImplicitParam(name = "comment", value = "评论表实体", paramType = "query", dataType = "Comment")
    @GetMapping("/list")
    public Result list(Comment comment) {
        if(StringUtils.isNull(comment)){
            return Result.error("实体类不能为空");
        }
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<Comment>(comment);
        List<Comment> list = commentService.list(queryWrapper);
        return Result.success().put("rows", list);
    }

    /**
     * 根据主键查询评论表
     */
    @ApiOperation("根据主键查询评论表")
    @ApiImplicitParam(name = "id", value = "主键", required = true, paramType = "path", dataType = "long")
    @GetMapping("/single/{id}")
    public Result single(@PathVariable("id") Long id) {
        return Result.success().put("obj", commentService.getById(id));
    }

    /**
     * 保存评论表
     */
    @PreAuthorize("@ps.hasPermission('sys:comment:save')")
    @Log(logtype = LogType.ALL,content ="保存",businessType = BusinessType.INSERT)
    @ApiOperation(value = "创建评论表", notes = "创建评论表")
    @ApiImplicitParam(name = "comment", value = "评论表实体", paramType = "body", dataType = "Comment")
    @PostMapping("/save")
    public Result save(@Valid @RequestBody Comment comment, BindingResult result){
        if (result.hasErrors()) {
        throw new CustomException(result.getFieldError().getDefaultMessage());
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        comment.setUserId(loginUser.getUser().getUserId());
        comment.setProfile(loginUser.getUser().getProfile());
        return Result.success().put("flag", commentService.save(comment));
    }

    /**
     * 修改评论表
     */
    @PreAuthorize("@ps.hasPermission('sys:comment:update')")
    @Log(logtype = LogType.PARAMETER,content ="修改",businessType = BusinessType.UPDATA)
    @ApiOperation(value = "修改评论表", notes = "修改评论表")
    @ApiImplicitParam(name = "comment", value = "评论表实体", paramType = "body", dataType = "Comment")
    @PutMapping("/update")
    public Result update(@RequestBody Comment comment){
        return Result.success().put("flag", commentService.updateById(comment));
    }

    /**
     * 根据主键删除评论表
     */
    @PreAuthorize("@ps.hasPermission('sys:comment:del')")
    @Log(logtype = LogType.PARAMETER,content ="删除",businessType = BusinessType.DELETE)
    @ApiOperation(value = "根据主键删除评论表", notes = "根据主键删除评论表")
    @ApiImplicitParam(name = "id", value = "评论表主键", required = true, paramType = "path", dataType = "long")
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable("id") Long id){
        return Result.success().put("flag", commentService.removeById(id));
    }

    /**
     * 批量删除评论表
     */
    @PreAuthorize("@ps.hasPermission('sys:comment:del')")
    @Log(logtype = LogType.PARAMETER,content ="批量删除",businessType = BusinessType.DELETE)
    @ApiOperation(value = "批量删除评论表", notes = "根据主键批量删除评论表")
    @ApiImplicitParam(name = "ids", value = "主键数组", required = true, paramType = "query", allowMultiple = true, dataType = "Long")
    @DeleteMapping("/dels")
    public Result del(@RequestParam(value = "ids[]") Long[] ids) {
        return Result.success().put("flag", commentService.removeByIds(Arrays.asList(ids)));
    }


    /**
     * 批量更改评论表的状态
     */
    @PreAuthorize("@ps.hasPermission('sys:comment:status')")
    @ApiOperation(value="批量更改评论表的状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "主键数组",required = true, paramType="query",allowMultiple=true,dataType="long"),
            @ApiImplicitParam(name="status",value = "状态数字",required = true, paramType="query",allowMultiple=false,dataType="Integer")
    })
    @PostMapping("/status")
    public Result status(Integer []ids, String status){
        if (StringUtils.isEmpty(status)){
        throw new CustomException("状态错误");
        }else if(ArrayUtil.isEmpty(ids)){
        throw new CustomException("主键数组错误");
        }
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("status",status);
        ArrayList<Comment> list = new ArrayList<>();
        for (Integer id : ids) {
        Comment entity = new Comment();
        entity.setStatus(status);
        entity.setCommentId(id);
        list.add(entity);
        }
        return Result.success().put("flag",commentService.updateBatchById(list));
    }
}
